package com.skstudio.report;

import java.util.ArrayList;

public class ReportProcess extends ReportBase {
	public long mInitRSS = 0, mMaxRSS = 0, mMinRSS = 0;
	public long mMaxThreads = 0; 
	public long mPid = 0;
	public float mMaxCPUPct = 0;
	
	public static class DataProc {
		public long mPid, mState, mThreads, mVSS, mRSS, mCpuTime;
		public float mPctUser, mPctKernel;
		
		public void Read(byte[] buffer, int offset) {
			mPid = getCxxUnsignedLong(buffer, offset + 0);
			mState = getCxxUnsignedLong(buffer, offset + 4);
			float value = getCxxUnsignedLong(buffer, offset + 8);
			mPctUser = value / 100.0f;
			value = getCxxUnsignedLong(buffer, offset + 12);
			mPctKernel = value / 100.0f;
			mVSS = getCxxUnsignedLong(buffer, offset + 16);
			mRSS = getCxxUnsignedLong(buffer, offset + 20);
			mThreads = getCxxUnsignedLong(buffer, offset + 24);
			mCpuTime = getCxxUnsignedLong(buffer, offset + 28);
		}
	}
	
	public ArrayList < DataProc > mDataList = new ArrayList < DataProc > ();
	
	boolean mbDead = false;
	
	@Override
	public void reset() {
		mDataList.clear();
		
		mPid = 0;
		mInitRSS = mMaxRSS = mMinRSS = 0;
		mMaxThreads = 0; 
		mMaxCPUPct = 0;
		
		mProcName = null;
		
		mbDead = false;
	}
	
	public boolean isDead() {
		return mbDead;
	}
	
	public int getDataSize() {
		return mDataList.size();
	}
	
	@Override
	public void parse(byte[] buffer, int offset)
	{
		DataProc dc = new DataProc();
		dc.Read(buffer, offset);
		if (dc.mPid == 0) {
			mbDead = true;
			return; //process is dead
		}
		
		if (mDataList.size() == getMaxQueueSize()) {
			mDataList.remove(0);
		}
		
		mPid = dc.mPid;
		
		if (mInitRSS == 0) {
			mInitRSS = mMinRSS = mMaxRSS = dc.mRSS;
		}
		if (mMaxRSS < dc.mRSS) {
			mMaxRSS = dc.mRSS;
		}
		if (mMinRSS > dc.mRSS) {
			mMinRSS = dc.mRSS;
		}
		if (mMaxThreads < dc.mThreads) {
			mMaxThreads = dc.mThreads;
		}
		if (mMaxCPUPct < dc.mPctUser + dc.mPctKernel) {
			mMaxCPUPct = dc.mPctUser + dc.mPctKernel;
		}
		/*String xx = String.format("%d (%s) CPU %f VSS %d, RSS %d", 
				dc.mPid, dc.mName,
				dc.mPctKernel + dc.mPctUser, dc.mVSS, dc.mRSS);
		Log.v("DataProc", xx);*/
		
		mDataList.add(dc);	
	}
	
	public String mProcName = null;
}
